package com.yuyou.fn.educational.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.constant.Constants;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.educational.entity.*;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.CriteriaUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.educational.vo.CourseTemplateQueryVo;
import com.yuyou.fn.educational.vo.CourseTemplateSaveOrUpdateVo;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.platform.service.IBusTeamService;
import org.springframework.stereotype.Service;

import com.yuyou.fn.educational.mapper.CourseTemplateMapper;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * CourseTemplate 表数据服务层接口实现类
 */
@Service
public class CourseTemplateServiceImpl extends SuperServiceImpl<CourseTemplateMapper, CourseTemplate, Long> implements ICourseTemplateService {

    @Resource
    private ICourseTypeService courseTypeService;

    @Resource
    private IAreaTeamService areaTeamService;

    @Resource
    private IBusTeamService busTeamService;

    @Resource
    private IBaseGradeService baseGradeService;

    @Resource
    private IBaseSubjectService baseSubjectService;



    @Resource
    private IProductService productService ;

    @Resource
    private ICourseClassService courseClassService ;

    @Override
    public Page<CourseTemplate> findCourseTemplateByQueryForPage(CourseTemplateQueryVo courseTemplateQuery, int pageNo, int pageSize) {
        Example<CourseTemplate> example = CourseTemplate.createExample();
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();

        CriteriaUtils.fillCondition(criteria, courseTemplateQuery);

        return findPageByExample(example, pageNo, pageSize);
    }

    @Override
    public void saveOrUpdateCourseTemplateList(CourseTemplateSaveOrUpdateVo courseTemplateSaveOrUpdateVo) {

        CourseTemplate courseTemplate = new CourseTemplate();

        BeanUtils.copyProperties(courseTemplate, courseTemplateSaveOrUpdateVo);
        checkCourse(courseTemplate);
        fillExtraData(courseTemplate);

        saveOrUpdate(courseTemplate);
    }

    private void checkCourse(CourseTemplate courseTemplate) {
        Example<CourseTemplate> example = CourseTemplate.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("areaTeamId",courseTemplate.getAreaTeamId()).andEqualTo("courseName" , courseTemplate.getCourseName() );

        CourseTemplate one = findOneByExample(example);
        if(one != null && ( courseTemplate.getCourseTemplateId() == null || !one.getCourseTemplateId().equals(courseTemplate.getCourseTemplateId()))){
            throw new BusException("课程名重复");
        }
    }

    @Override
    public void changeCourseStatus(Long courseTemplateId, Integer status) {

        if (status != 0 && status != 1) {
            throw new IllegalArgumentException("Invalid status");
        }

        CourseTemplate courseTemplate = new CourseTemplate();
        courseTemplate.setCourseTemplateId(courseTemplateId);
        courseTemplate.setStatus(status);
        updateSelectiveById(courseTemplate);

    }

    @Override
    public List<CourseTemplate> findBaseCourseForList(Long areaTeamId) {
        Example<CourseTemplate> example = CourseTemplate.createExample();
        Example.Criteria criteria = example.createCriteria();
        example.selectProperties("courseName");
        //criteria.andEqualTo("status" , 1 ) ;
        CriteriaUtils.fillCondition(criteria,areaTeamId,null);
        return findListByExample(example);
    }

    @Transactional
    @Override
    public void saveOrUpdateCourseTemplateList(List<CourseTemplate> courseTemplateList,SysUser user) {
        if ( courseTemplateList.size()!=0){

            for (CourseTemplate courseTemplate : courseTemplateList) {

                String areaTeamName = courseTemplate.getAreaTeamName();
                AreaTeam areaTeam = areaTeamService.findAreaTeamByName(areaTeamName);

                if(areaTeam == null ){
                    throw new BusException("无法识别区域：" + areaTeamName );
                }

                if( user.getUserType() != Constants.USER_TYPE_OF_YUYOU ){
                    if( !areaTeam.getAreaTeamId().equals(user.getAreaTeamId())){
                        throw new BusException("你无权限上传此区域：" + areaTeamName );
                    }
                    courseTemplate.setAreaTeamId(user.getAreaTeamId());
                    courseTemplate.setBusTeamId(user.getBusTeamId());
                    courseTemplate.setAreaTeamName(user.getAreaTeamName());
                    courseTemplate.setBusTeamName(user.getBusTeamName());
                }else{
                    courseTemplate.setAreaTeamId(areaTeam.getAreaTeamId());
                    courseTemplate.setBusTeamId(0l);
                    courseTemplate.setAreaTeamName(areaTeam.getName());
                    courseTemplate.setBusTeamName("");
                }


                String gradeName = courseTemplate.getGradeName();
                BaseGrade baseGrade = baseGradeService.findGradeByGradeName(gradeName);
                if(baseGrade == null ){
                    throw new BusException("无法识别年级：" + gradeName );
                }
                courseTemplate.setGradeId(baseGrade.getGradeId());
                String subjectName = courseTemplate.getSubjectName();
                BaseSubject subject = baseSubjectService.findSubjectBySubjectName(subjectName);
                if(subject == null ){
                    throw new BusException("无法识别科目：" + subjectName );
                }
                courseTemplate.setSubjectId(subject.getSubjectId());

                String productName = courseTemplate.getProductName();
                Product product = productService.findProductByNameAreaTeamId(productName,courseTemplate.getAreaTeamId() );
                if(product == null ){
                    throw new BusException("无法识别产品名：" + productName );
                }
                courseTemplate.setProductId(product.getProductId());
                String courseTypeName = courseTemplate.getCourseTypeName();
                CourseType courseType = courseTypeService.findCourseTypeByName(courseTypeName);
                if(courseType == null ){
                    throw new BusException("无法识别课程类型：" + courseTypeName );
                }
                courseTemplate.setCourseTypeId(courseType.getCourseTypeId());
                this.saveOrUpdate(courseTemplate);
            }
        }else{
            throw new BusException("请检查导入文件");
        }
    }


    private void saveOrUpdate(CourseTemplate courseTemplate) {
        checkCourse(courseTemplate);
        if (courseTemplate.getCourseTemplateId() == null) {
            courseTemplate.setCreateTime(TimeUtils.now());
            courseTemplate.setUpdateTime(TimeUtils.now());
            insertSelective(courseTemplate);
        } else {
            courseTemplate.setUpdateTime(TimeUtils.now());
            updateSelectiveById(courseTemplate);
        }
    }

    private void fillExtraData(CourseTemplate courseTemplate) {

        if (courseTemplate.getAreaTeamId() != null) {
            courseTemplate.setAreaTeamName(areaTeamService.findTeamNameById(courseTemplate.getAreaTeamId()));
        } else {
            courseTemplate.setAreaTeamId(0l);
            courseTemplate.setAreaTeamName("");
        }

        if (courseTemplate.getBusTeamId() != null) {
            courseTemplate.setBusTeamName(busTeamService.findTeamNameById(courseTemplate.getBusTeamId()));
        } else {
            courseTemplate.setBusTeamId(0l);
            courseTemplate.setBusTeamName("");
        }

        if (courseTemplate.getCourseTypeId() != null) {
            courseTemplate.setCourseTypeName(courseTypeService.findCourseTypeNameById(courseTemplate.getCourseTypeId()));
        } else {
            courseTemplate.setCourseTypeId(0l);
            courseTemplate.setCourseTypeName("");
        }

        if (courseTemplate.getGradeId() != null) {
            courseTemplate.setGradeName(baseGradeService.findGradeNameById(courseTemplate.getGradeId()));
        } else {
            courseTemplate.setGradeId(0l);
            courseTemplate.setGradeName("");
        }

        if (courseTemplate.getSubjectId() != null) {
            courseTemplate.setSubjectName(baseSubjectService.findGradNameById(courseTemplate.getSubjectId()));
        } else {
            courseTemplate.setSubjectId(0l);
            courseTemplate.setSubjectName("");
        }
        if (courseTemplate.getProductId()!=null) {
            courseTemplate.setProductName(productService.findProductNameById(courseTemplate.getProductId()));
        } else {
            courseTemplate.setProductId(0l);
            courseTemplate.setProductName("");
        }

    }

    @Override
    public void deleteCourse(Long courseTemplateId) {

        Example<CourseClass> courseClassExample = CourseClass.createExample();

        courseClassExample.createCriteria().andEqualTo("courseTemplateId",courseTemplateId);

        long l = courseClassService.countByExample(courseClassExample);

        if(l > 0 ){
            throw new BusException("课程模板已经被使用了，无法删除");
        }
        deleteById(courseTemplateId);
    }
}